

import 'package:flutter/cupertino.dart';
import 'package:flutter_book/api/api_common.dart';
import 'package:flutter_book/config/application.dart';
import 'package:flutter_book/constant/color.dart';
import 'package:flutter_book/data/database/yck_rule_helper.dart';
import 'package:flutter_book/data/model/yck/rule/single/single_rule.dart';
import 'package:flutter_book/data/model/yck/yck_rule_book_3_model.dart';
import 'package:flutter_book/route/router.dart';
import 'package:flutter_book/util/analyze/analyze_yck_rule_book_util.dart';
import 'package:flutter_book/widget/diglog/app_dialog.dart';
import 'package:flutter_book/widget/diglog/common_dialog.dart';
import 'package:get/get.dart';
import 'package:flutter_book/util/extensions/string_extensions.dart';
import 'package:flutter_book/util/extensions/widget_extensions.dart';

import 'backstage/scan_yck/yck_source_list_page.dart';

class BookSourcePage extends StatefulWidget {
  @override
  _BookSourcePageState createState() => _BookSourcePageState();
}

class _BookSourcePageState extends State<BookSourcePage> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  SourceValueController sourceValueController = SourceValueController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    sourceValueController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      color: AppColor.white,
      child: Column(
        children: [
          GestureDetector(
            onTap: () {
              AppRouter.toScanQRCodePage((dynamic result) {
                if (result is String) {
                  sourceValueController.setValue(result);
                } else {
                  AppDialog.showImportSourceDialog(context, result, onExitListener: () {
                    sourceValueController.setValue("资源列表的数据：${Application.yckRuleModelMap.length}个");
                    sourceValueController.setModelList();
                  });
                }
              });
            },
            child: Text("扫一扫"),
          ),
          Obx(
            () => Container(
              color: AppColor.mainRed,
              height: 50,
              width: Get.width,
              child: Text("测试全部:${sourceValueController.modelList.length}"),
            ).onTap(_onClickTestAllUrl),
          ),
          Obx(
            () => Container(
              child: Text(sourceValueController.value.value),
            ),
          ),
          Expanded(
              child: SizedBox(
            child: Obx(
              () => ListView.builder(
                    itemCount: sourceValueController.modelList.length,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        onTap: () {
                          _onTestSingeItem(sourceValueController.modelList[index]);
                          // AppRouter.toSourceAnalyzePage(sourceValueController.modelList[index]);
                        },
                        onLongPress: () {
                          _sourceLongPress(sourceValueController.modelList[index]);
                        },
                        child: Container(
                          color: AppColor.mainBlue,
                          padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                          margin: EdgeInsets.symmetric(vertical: 8),
                          child: Text(sourceValueController.modelList[index].bookSourceName),
                    ),
                      );
                    },
                  ),
            ),
          )),
        ],
      ),
    );
  }


  _sourceLongPress(YckRuleBook3Model model) {
    AppDialog.showCommonDialog(
        context,
        title: "删除消息",
        info: "确认删除这个资源吗？",
        barrierDismissible: false,
        cancel: AppDialogButton("取消", () {
          "点了取消".print;
          return true;
        }),
        confirm: AppDialogButton("确定", () {
          Application.yckRuleModelMap.remove(model.id);
          sourceValueController.setModelList();
          YckRuleHelper.init().remove(model);
          return true;
        }));
  }


  _onClickTestAllUrl() {
    sourceValueController.modelList.forEach((element) {
      _onTestSingeItem(element);
    });
  }

  _onTestSingeItem(YckRuleBook3Model element) async {
    if (element.ruleSearch == null) {
      "没有搜索规则".print;
    } else if (element.ruleSearch!.bookList is SingleRule) {
      AnalyzeYckRuleBookUtil.init().searchBookList(element, "斗罗大陆", 0);
    } else {
      "搜索规则没有解析正确:${element.bookSourceName}".print;
    }
  }
}

class SourceValueController extends GetxController {
  var value = "".obs;
  var modelList = <YckRuleBook3Model>[].obs;

  setValue(String value) => this.value.value = value;

  initData() async {
    Application.yckRuleModelMap = await YckRuleHelper.init().getAllMap();
    setModelList();
  }

  setModelList() {
    List<YckRuleBook3Model> yckRuleModelList = [];
    Application.yckRuleModelMap.forEach((key, value) {
      yckRuleModelList.add(value);
    });
    modelList.clear();
    modelList.addAll(yckRuleModelList);
  }

  @override
  void onClose() {
    super.onClose();
  }

  @override
  void onInit() {
    super.onInit();
    initData();
  }

  @override
  void onReady() {
    super.onReady();
  }
}


